package cc.zzone.controller;

import cc.zzone.bean.Result;
import cc.zzone.domain.FileRes;
import cc.zzone.util.SpringMVCUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 数据资源接口
 *
 * @author jinzhengze
 * @since 2023年10月15日
 */
@RestController
@RequestMapping("/res")
public class ResController {

    private static final MessageDigest MD5;

    static {
        try {
            MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    Object uploadFile(@RequestPart("file") MultipartFile file,
                      @RequestParam(required = false) String id) throws Exception {
        if (FileRes.mapper().getData(id) != null)
            throw new RuntimeException("自定义ID已存在对应资源");
        FileRes res = new FileRes();
        byte[] bytes = file.getBytes();
        byte[] digest = MD5.digest(bytes);
        res.setId(StringUtils.hasText(id) ? id : new BigInteger(1, digest).toString(16));
        res.setName(file.getOriginalFilename());
        res.setFile(bytes);
        FileRes.mapper().insertData(res);
        return Result.success(res.getId());
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    Object fileList() {
        return Result.success(FileRes.mapper().listData(null));
    }

    @RequestMapping(method = RequestMethod.DELETE)
    Object deleteData(@RequestBody String[] ids) {
        return Result.success(FileRes.mapper().deleteData(ids));
    }

    @RequestMapping(method = RequestMethod.GET)
    void getFile(@RequestParam String id, @RequestParam(required = false) Boolean base64) throws IOException {
        FileRes data = FileRes.mapper().getData(id);
        if (data == null)
            throw new RuntimeException("文件不存在");
        HttpServletResponse response = SpringMVCUtil.getResponse();
        assert response != null;
        ServletOutputStream outputStream = response.getOutputStream();
        if (base64 != null && base64) {
            String[] split = data.getName().split("\\.");
            String head = "data:image/png;base64,";
            if (split.length == 2) {
                if ("svg".equalsIgnoreCase(split[1])) head = "data:image/svg+xml;base64,";
                else head = "data:image/" + split[1] + ";base64,";
            }
            String base64URL = head + Base64.getEncoder().encodeToString(data.getFile());
            FileCopyUtils.copy(new ByteArrayInputStream(base64URL.getBytes()), outputStream);
            return;
        }
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;parameter=" +
                URLEncoder.encode(data.getName(), StandardCharsets.UTF_8));
        FileCopyUtils.copy(new ByteArrayInputStream(data.getFile()), outputStream);
    }
}
